package com.cuitrip.business.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.business.location.model.AreaMode;
import com.cuitrip.business.location.model.LocationMode;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.user.presenter.CityChoosePresenter;
import com.cuitrip.business.user.presenter.ICityView;
import com.cuitrip.business.user.ui.CityChooseAdapter;
import com.cuitrip.business.webview.H5UrlMaker;
import com.cuitrip.business.webview.proxy.WebViewProxy;
import com.cuitrip.component.item.CustomIndexBar;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.lab.app.BaseFragment;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by sheena on 16/3/4.
 */
public class ChooseCityActivity extends CustomUiFragmentActivity implements ICityView {
    public static final int PROFILE_MODE = 0x01;
    public static final int SERVICE_MODE = 0x02;
    public static final String CITY_NAME_KEY = "CITY_NAME_KEY";
    public static final String CITY_ABBR_KEY = "CITY_ABBR_KEY";
    public static final String COUNTRY_NAME_KEY = "COUNTRY_NAME_KEY";
    public static final String COUNTRY_ABBR_KEY = "COUNTRY_ABBR_KEY";
    public static final String ADDRESS_KEY = "ADDRESS_KEY";
    public static final int REQUEST_CHOOSE_LOCATION = 8888;
    public static final String KEY_CHOOSE_MODE = "choose_mode";
    public static final String CREATE_TRIP_LOCATION = "location";
    public static final String SHOW_LOCAITON_HINT_FLAG="show_locaiton_hint_flag";
    @Bind(R.id.city_list)
    ListView mCityList;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;
    @Bind(R.id.index_bar)
    CustomIndexBar mIndexBar;
    @Bind(R.id.tv_create_city_desc)
    TextView tvDesc;
    @Bind(R.id.tv_ambassador_link)
    TextView tvAmbassadorLink;
    private int chooseMode = PROFILE_MODE;
    private CityChoosePresenter cityChoosePresenter;
    private String abbr = "";
    private LocationMode locationMode;
    private CityChooseAdapter adapter;
    private String countryAbbr;
    private String countryName;
    private String cityAbbr;
    private String cityName;
    private String address;
    private String userType = ServiceBusiness.USER_TYPE;
    private boolean isShow;


    public static void chooseLocation(Activity activity, int chooseMode,boolean isShow) {
        Intent intent = new Intent(activity, ChooseCityActivity.class);
        intent.putExtra(KEY_CHOOSE_MODE, chooseMode);
        intent.putExtra(SHOW_LOCAITON_HINT_FLAG,isShow);
        activity.startActivityForResult(intent, REQUEST_CHOOSE_LOCATION);
    }

    public static void chooseLocation(BaseFragment fragment, int chooseMode,boolean isShow) {
        Intent intent = new Intent(fragment.getHostActivity(), ChooseCityActivity.class);
        intent.putExtra(KEY_CHOOSE_MODE, chooseMode);
        intent.putExtra(SHOW_LOCAITON_HINT_FLAG,isShow);
        fragment.startActivityForResult(intent, REQUEST_CHOOSE_LOCATION);
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        if(isShow){
            config.mTopbarMiddleAreaName=getString(R.string.trip_attribute_destination_desc_3);
        }else{
            config.mTopbarMiddleAreaName = getString(R.string.setting_country);
        }
        return config;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getIntent() == null) {
            finish();
        }
        chooseMode = getIntent().getIntExtra(KEY_CHOOSE_MODE, PROFILE_MODE);
        isShow = getIntent().getBooleanExtra(SHOW_LOCAITON_HINT_FLAG, false);
        cityChoosePresenter = new CityChoosePresenter();
        cityChoosePresenter.attachView(this);
        super.onCreate(savedInstanceState, R.layout.activity_choose_city);

    }

    @Override
    public void initView() {
        ButterKnife.bind(this);

    }


    @Override
    public void initData() {
        if (chooseMode == SERVICE_MODE) {
            userType = ServiceBusiness.SERVICE_TYPE;
            if (isShow) {
                tvDesc.setVisibility(View.VISIBLE);
                tvAmbassadorLink.setVisibility(View.VISIBLE);
                String text = getString(R.string.TRIP_ATTRIBUTE_DESTINATION_DESC_2);
                SpannableString spannableString = new SpannableString(text);
                spannableString.setSpan(new UnderlineSpan(), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvAmbassadorLink.setText(spannableString);
                tvAmbassadorLink.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WebViewProxy.getInstance().browseWeb(ChooseCityActivity.this, H5UrlMaker.getAmbaURL(LoginInstance.getInstance().getUserInfo().getUid()));
                    }
                });
            }else{
                tvDesc.setVisibility(View.GONE);
                tvAmbassadorLink.setVisibility(View.GONE);
            }

        }
        cityChoosePresenter.loadLocationMode(new AreaMode(getString(R.string.setting_country), null, ""), userType);

    }


    private String getFormatAddress(Stack<CityChoosePresenter.LocationPoint> stack, AreaMode lastAreaMode) {
        int size = stack.size();
        //因为第一层是请求空的参数
        boolean isZXS = cityChoosePresenter.isZXS(lastAreaMode.getAbbr());
        if (isZXS) {
            //直辖市两层
            if (size == 3) {
                StringBuilder stringBuilder = new StringBuilder(stack.get(1).title);
                stringBuilder.append("-").append(stack.get(2).title);
                return stringBuilder.toString();
            }
        } else {
            //单级地名 如新加坡
            if (size == 1) {
                StringBuilder stringBuilder = new StringBuilder(lastAreaMode.getName());
                return stringBuilder.toString();
            } else {
                StringBuilder stringBuilder = new StringBuilder(stack.get(1).title);
                stringBuilder.append("-").append(lastAreaMode.getName());
                return stringBuilder.toString();
            }
        }
        return "";
    }

    @Override
    public void initListener() {

        mCityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<AreaMode> content = locationMode.getContent();
                if (content != null) {
                    AreaMode areaMode = content.get(position);
                    abbr = areaMode.getAbbr();
                    int hasChild = areaMode.getHasChild();
                    if (hasChild == 1) {
                        //如果有下一级，点击再次请求
                        tvDesc.setVisibility(View.GONE);
                        tvAmbassadorLink.setVisibility(View.GONE);
                        countryAbbr = areaMode.getAbbr();
                        countryName = areaMode.getName();
                        cityChoosePresenter.loadLocationMode(areaMode, userType);
                    } else {
                        Stack<CityChoosePresenter.LocationPoint> stack = cityChoosePresenter.getStack();
                        if (stack.size() < 1) {
                            return;
                        }
                        if (stack.size() > 1) {
                            countryAbbr = stack.get(1).abbr;
                            countryName = stack.get(1).title;
                        } else {
                            countryAbbr = areaMode.getAbbr();
                            countryName = areaMode.getName();

                        }

                        address = getFormatAddress(stack, areaMode);

                        cityName = areaMode.getName();
                        cityAbbr = areaMode.getAbbr();

                        if (chooseMode == PROFILE_MODE) {
                            showNoCancelDialog();
                            cityChoosePresenter.saveCity(countryAbbr, cityAbbr, address);
                        } else if (chooseMode == SERVICE_MODE) {
                            success();
                        }
                    }

                }
            }
        });

    }


    @Override
    public void renderUi(LocationMode locationMode, ArrayList<String> list, HashMap<String, Integer> map) {
        this.locationMode = locationMode;
        List<AreaMode> content = locationMode.getContent();
        List<String> areas=new ArrayList<>();
        for (AreaMode area:content){
            String name = area.getName();
            areas.add(name);
        }
        adapter = new CityChooseAdapter();
        adapter.setData(locationMode, map);
        mCityList.setAdapter(adapter);
        String s = list.toString().replaceAll(", ", "");
        String substring = s.substring(1, s.length() - 1);
        mIndexBar.setData(substring,mCityList);
    }


    @Override
    public void displayLoading() {
        mStateLayout.changeState(StateLayout.State.Loading);
    }

    @Override
    public void displayContent() {
        mStateLayout.changeState(StateLayout.State.INIT);
    }

    @Override
    public void displayEmpty() {
        mStateLayout.changeState(StateLayout.State.Empty);
    }

    @Override
    public void displayNoNetwork() {
        mStateLayout.changeState(StateLayout.State.NoNetwork);
    }

    @Override
    public void displayLoadingDialog() {
        showLoading();
    }

    @Override
    public void hideLoadingDialog() {
        hideLoading();
    }

    @Override
    public void success() {
        //！！！调用地方不止一出，不要轻易修改
        Intent intent = new Intent();
        intent.putExtra(CITY_NAME_KEY, cityName);
        intent.putExtra(CITY_ABBR_KEY, cityAbbr);
        intent.putExtra(COUNTRY_NAME_KEY, countryName);
        intent.putExtra(COUNTRY_ABBR_KEY, countryAbbr);
        intent.putExtra(ADDRESS_KEY, address);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void onTopbarLeftPress() {
        Stack<CityChoosePresenter.LocationPoint> stack = cityChoosePresenter.getStack();
        if (stack.isEmpty()) {
            finish();
            return;
        }
        stack.pop();
        if (stack.empty()) {
            this.setResult(RESULT_CANCELED);
            this.finish();
        } else {
            CityChoosePresenter.LocationPoint state = stack.peek();
            mTopbarMiddleArea.setText(state.title);
            renderUi(state.locationMode, state.index, state.indexMap);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
